package net.app.help.dialogs;

import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import net.app.help.R;
import net.app.help.db.DatabaseAdapter;
import net.app.help.model.Message;

/**
 * Created by Boogaboo on 22.1.2015.
 */
public class EditMessageDialog extends DialogFragment {

	private EditText title;
	private EditText content;
	private Button confirm;

	private Message selectedMessage;

	private DatabaseAdapter da;

	private OnConfirmInterface callback;


	public static EditMessageDialog newInstance(Message m) {
		EditMessageDialog egd = new EditMessageDialog();
		egd.selectedMessage = m;
		return egd;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			callback = (OnConfirmInterface) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnConfirmInterface.");
		}
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_edit_message, null);

		da = new DatabaseAdapter(getActivity());
		title = (EditText) v.findViewById(R.id.frag_edit_msg_et_edit_title);
		title.setText(String.valueOf(selectedMessage.getTitle()));
		content = (EditText) v.findViewById(R.id.frag_edit_msg_et_content);
		content.setText(String.valueOf(selectedMessage.getContent()));
		confirm = (Button) v.findViewById(R.id.frag_edit_msg_b_confirm);
		confirm.setOnClickListener(confirmListener);

		return v;
	}

	private View.OnClickListener confirmListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
//			IMPLEMENTIRAJ SHRANJEVANJE NOVEGA STANJA - NAME,...?
			if (!title.getText().toString().equals(selectedMessage.getTitle())) {
				selectedMessage.setTitle(title.getText().toString());
				da.openToWrite();
				da.updateMessage(selectedMessage);
				da.close();
			}
			if (!content.getText().toString().equals(selectedMessage.getContent())) {
				selectedMessage.setContent(content.getText().toString());
				da.openToWrite();
				da.updateMessage(selectedMessage);
				da.close();
			}
			callback.onConfirmEditMessage();
			dismiss();
		}
	};

	public interface OnConfirmInterface {
		public void onConfirmEditMessage();
		public void onCancelEditMessage();
	}

}
